package org.example4;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

import java.lang.reflect.Method;

public class AppMain {
    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass targetClass = pool.get("org.example4.MyClass");
        CtMethod targetMethod = targetClass.getDeclaredMethod("myMethod");

        // 在方法调用前注入代码
        targetMethod.instrument(new ExprEditor() {
            @Override
            public void edit(MethodCall m) throws CannotCompileException {
                m.replace("System.out.println(\"Before method call: \" + $1); $_ = $proceed($$);");
            }
        });

        Class<?> modifiedClazz = targetClass.toClass();
        Method myMethod = modifiedClazz.getDeclaredMethod("myMethod");
        Object o = modifiedClazz.newInstance();
        myMethod.invoke(o);

    }
}
